/**
 * 更新资源数
 */
Parse.Cloud.beforeSave('RcResource', async (req, res) => {

  try {
    const resource = req.object
    if (resource.id) {
      const deleted = resource.get('deleted')
      if (deleted) {
        const prev = await new Parse.Query('RcResource').equalTo('objectId', resource.id).include('circle').first()
        const preDeleted = prev.get('deleted')
        if (deleted !== preDeleted) {
          const circle = prev.get('circle')
          const member = circle.get('member')
          circle.increment('resourceTotal',-1).save()
          member.increment('resourceTotal', -1).save()
        }
      }
      res.success()
    } else {
      res.success()
      // 更新圈子的资源数
      const circle = resource.get('circle')
      circle.increment('resourceTotal', 1).set('lastResourceTitle', resource.get('title')).set('lastUpdateTime',new Date())

      // 更新用户圈子的新提醒数
      const memberCircle = await new Parse.Query('RcMemberCircle').equalTo('circle', circle).limit(1000000).find()

      const tasks = []
      memberCircle.map(item => {
        item.increment('newTotal', 1)
        const member = item.get('member')
        member.increment('newResourceTotal', 1)

        tasks.push(member)
        tasks.push(item)
      })

      tasks.push(circle)
      Parse.Object.saveAll(tasks)

      const currentCircle = await new Parse.Query('RcCircle').equalTo('objectId', circle.id).first()
      const member = currentCircle.get('member')
      member.increment('resourceTotal', 1).save()
    }
  } catch (err) {
    console.log(err)
  }
})

